package comment_api

import (
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/service/redis"
	"github.com/gin-gonic/gin"
	"github.com/liu-cn/json-filter/filter"
	"gorm.io/gorm"
)

type CommentListRequest struct {
	ArticleID string `form:"article_id" binding:"required" msg:"请选择文章"`
}

func (CommentApi) CommentListView(c *gin.Context) {
	var cr CommentListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}
	rootCommentList := FindArticleCommentList(cr.ArticleID)
	data := filter.Select("c", rootCommentList)
	if len(rootCommentList) <= 0 {
		data = make([]models.CommentModel, 0)
	}
	http.IsOkWithData(data, c)
}

func FindArticleCommentList(articleID string) (RootCommentList []*models.CommentModel) {
	// 先把文章下的根评论查出来
	common.DB.Preload("User").Find(&RootCommentList, "article_id = ? AND parent_comment_id is null", articleID)
	// 遍历评论, 递归查评论下的所有评论
	diggInfo := redis.NewCommentDiggCount().GetInfoAll()
	for _, model := range RootCommentList {
		var subCommentList, newSubCommentList []models.CommentModel
		FindSubComment(*model, &subCommentList)
		for _, commentModel := range subCommentList {
			digg := diggInfo[fmt.Sprintf("%d", commentModel.ID)]
			commentModel.LikeCount = commentModel.LikeCount + digg
			newSubCommentList = append(newSubCommentList, commentModel)
		}
		modelDigg := diggInfo[fmt.Sprintf("%d", model.ID)]
		model.LikeCount = model.LikeCount + modelDigg
		model.SubComments = newSubCommentList
	}
	return
}

// FindSubComment 递归查评论下的子评论
func FindSubComment(model models.CommentModel, subCommentList *[]models.CommentModel) {
	err := common.DB.Preload("SubComments.User").Take(&model).Error
	if err == gorm.ErrRecordNotFound {
		// 没有记录
		return
	}
	for _, sub := range model.SubComments {
		*subCommentList = append(*subCommentList, sub)
		FindSubComment(sub, subCommentList)
	}
	return
}

// FindSubCommentCount 获取评论数
func FindSubCommentCount(model models.CommentModel) (subCommentList []models.CommentModel) {
	findSubCommentList(model, &subCommentList)
	return subCommentList
}

func findSubCommentList(model models.CommentModel, subCommentList *[]models.CommentModel) {
	err := common.DB.Preload("SubComments").Take(&model).Error
	if err == gorm.ErrRecordNotFound {
		// 没有记录
		return
	}
	for _, sub := range model.SubComments {
		*subCommentList = append(*subCommentList, sub)
		FindSubComment(sub, subCommentList)
	}
	return
}
